_package("alz.mui");

_import("alz.mui.Component");

/**
 * 移动行为数据统计表
 */
_class("Table", Component, function(){
	this._init = function(){
		_super._init.call(this);
		this._total = null;
		this._lastV = 0;
		this._sign = 1;
	};
	this.create = function(parent, data){
		this.setData(this.formatData(data));
		var obj = this.createElement(parent, "div", "wui-Table");
		this.init(obj);
		return obj;
	};
	this.init = function(obj){
		_super.init.apply(this, arguments);
		for(var i = 1, len = this._data.length; i < len; i++){
			this.appendCol(obj, this._data[i]);
		}
	};
	this.dispose = function(){
		_super.dispose.apply(this);
	};
	this.formatData = function(data){
		var total = {
			"t"     : 0,  //时间总和
			"s"     : 0,  //距离总和
			"s_max" : 0,  //最大距离
			"ds_max": 0,  //最大距离差
			"v_max" : 0,  //最大速度
			"a_max" : 0   //最大加速度
		};
		this._sign = data[data.length - 1].s - data[1].s > 0 ? 1 : -1;
		for(var i = 1, len = data.length; i < len; i++){
			var item = data[i];  //每个元素的结构{t,s,v,dt,ds,a}
			var item0 = data[i - 1];  //前一个元素
			item.dt = item.t - item0.t;
			item.ds = item.s - item0.s;
			item.v = this._sign * item.s / item.t;
			item.a = (item.v - (i == 1 ? 0 : item0.v)) / item.dt;
			this._lastV = item.v;
			total.t += item.dt;
			total.s += item.ds;
			total.s_max  = Math.max(total.s_max, item.s);
			total.ds_max = Math.max(total.ds_max, item.ds);
			total.v_max  = Math.max(total.v_max, item.v);
			total.a_max  = Math.max(total.a_max, item.a);
		}
		this._total = total;
		return data;
	};
	this.getTotalData = function(){
		return {
			"v"   : this._lastV,
			"sign": this._sign
		};
	};
	this.appendCol = function(parent, data){
		var w = Math.round(300 * data.dt / this._total.t) - 1;
		var col = document.createElement("div");
		col.className = "col";
		col.style.width = w + "px";
		col.style.height = "180px";
		this.appendItem(col, w, 1, "red"    , Math.round(180 - 180 * data.s  / this._total.s_max ));
		this.appendItem(col, w, 2, "green"  , Math.round(180 - 180 * data.ds / this._total.ds_max));
		this.appendItem(col, w, 3, "blue"   , Math.round(180 - 180 * data.v  / this._total.v_max ));
		this.appendItem(col, w, 4, "#800080", Math.round(180 - 180 * data.a  / this._total.a_max ));
		col.title = runtime.forIn(data).join("\n");
		parent.appendChild(col);
	};
	this.appendItem = function(col, width, zIndex, bgcolor, top){
		var a = document.createElement("div");
		a.className = "n";
		a.style.width = width + "px";
		a.style.zIndex = zIndex;
		a.style.backgroundColor = bgcolor;
		a.style.top = top + "px";
		col.appendChild(a);
	};
});